document.addEventListener('DOMContentLoaded', function() {
    // 侧边栏折叠按钮
    const sidebarCollapse = document.getElementById('sidebarCollapse');
    const sidebar = document.getElementById('sidebar');
    const content = document.getElementById('content');
    
    if (sidebarCollapse) {
        sidebarCollapse.addEventListener('click', function () {
            sidebar.classList.toggle('active');
            content.classList.toggle('active');
        });
    }

    // 设置当前页面对应的导航项为激活状态
    const currentPath = window.location.pathname;
    document.querySelectorAll('#sidebar a').forEach(link => {
        if (link.getAttribute('href') === currentPath) {
            link.classList.add('active');
        }
    });

    // 根据当前页面加载相应的数据
    if (currentPath === '/' || currentPath === '/index') {
        fetch('/api/user-stats')
            .then(response => response.json())
            .then(data => {
                const totalUsers = document.getElementById('total-users');
                const activeUsers = document.getElementById('active-users');
                const vipUsers = document.getElementById('vip-users');
                
                if (totalUsers) totalUsers.textContent = data.total_users;
                if (activeUsers) activeUsers.textContent = data.active_users;
                if (vipUsers) vipUsers.textContent = data.vip_users;

                // 绘制消费得分分布图表
                if (data.consumption_distribution) {
                    const trace = {
                        x: Object.keys(data.consumption_distribution),
                        y: Object.values(data.consumption_distribution),
                        type: 'bar',
                        marker: {
                            color: '#007bff'
                        }
                    };

                    const layout = {
                        title: '用户消费得分分布',
                        xaxis: {
                            title: '消费得分区间'
                        },
                        yaxis: {
                            title: '用户数量'
                        }
                    };

                    Plotly.newPlot('consumption-chart', [trace], layout);
                }

                // 绘制会员等级分布图表
                if (data.membership_distribution) {
                    const trace = {
                        labels: Object.keys(data.membership_distribution),
                        values: Object.values(data.membership_distribution),
                        type: 'pie',
                        marker: {
                            colors: ['#28a745', '#17a2b8', '#ffc107', '#dc3545']
                        }
                    };

                    const layout = {
                        title: '会员等级分布'
                    };

                    Plotly.newPlot('membership-chart', [trace], layout);
                }
            })
            .catch(error => console.error('Error fetching user stats:', error));
    }
});
